﻿using Microsoft.Xna.Framework;

namespace Brain.Ballistics3D
{
    public class BulletManager3D : IUpdateable, IDrawable
    {
        public static BulletManager3D Instance;

        public Bullet3D[] Bullets { get; protected set; }

        public bool ShouldUpdate { get; set; }

        public bool ShouldDraw { get; set; }

        public IBulletRenderer3D BulletRenderer;

        private int curIndex;
        public int CurrentIndex
        {
            get { return curIndex; }
            set
            {
                curIndex = value;
                if (curIndex >= Bullets.Length)
                {
                    //Reset the Index
                    curIndex = 0;
                }
            }
        }

        public BulletManager3D(int maxBullets)
        {
            Instance = this;

            ShouldUpdate = true;
            ShouldDraw = true;

            Bullets = new Bullet3D[maxBullets];

            for (int i = 0; i < maxBullets; i++)
            {
                Bullets[i] = new Bullet3D(this);
            }
        }


        public void AddBullet(Vector3 position, Vector3 direction, float bulletSpeed, SetBullet3D onHit)
        {
            Bullet3D bullet = this.Bullets[CurrentIndex];
            bullet.Reset(direction, position, bulletSpeed, onHit);

            if (BulletRenderer != null)
            {
                BulletRenderer.UpdateParticle(bullet, CurrentIndex);
            }
            CurrentIndex++;
        }

        public void Update()
        {
            if (BulletRenderer == null ||
                BulletRenderer.ManagerUpdatesBullets)
            {
                for (int i = 0; i < Bullets.Length; i++)
                {
                    Bullets[i].Update();
                }
            }
        }

        public void Draw()
        {
            if (BulletRenderer != null)
            {
                BulletRenderer.Render(this);
            }
        }
    }
}
